{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-12T05:12:39.605784Z",
     "start_time": "2019-03-12T05:12:30.355777Z"
    }
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "GBDT-LR模型\n",
    " 1.准备GBDT输入的label encoding\n",
    " 2.准备GBDT输入的 one-hot encoding\n",
    " 3.建立GBDT-LR模型，并训练调参\n",
    " 4.预测结果    \n",
    "    \n",
    "\"\"\"\n",
    "\n",
    "##==================== 导入工具包 ====================##\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import random\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.ensemble import GradientBoostingClassifier\n",
    "from sklearn.linear_model import SGDClassifier  # using SGDClassifier for training incrementally\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from dummyPy import OneHotEncoder  # for one-hot encoding on a large scale of chunks\n",
    "from sklearn.metrics import log_loss\n",
    "import matplotlib.pyplot as plt\n",
    "import pickle\n",
    "import gc\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-12T05:12:39.630720Z",
     "start_time": "2019-03-12T05:12:39.608774Z"
    }
   },
   "outputs": [],
   "source": [
    "##==================== 文件路径 ====================##\n",
    "\n",
    "fp_train_f = \"feature_engineering/train_f.csv\"\n",
    "fp_test_f  = \"feature_engineering/test_f.csv\"\n",
    "## 子训练集\n",
    "#fp_sub_train_f = \"feature_engineering/sub_train_f.csv\"\n",
    "#fp_sub_test_f = \"feature_engineering/sub_test_f.csv\"\n",
    "\n",
    "## label encoder for gbdt input\n",
    "fp_lb_enc = \"feature_engineering/lb_enc\"\n",
    "\n",
    "## one-hot encoder for gbdt output\n",
    "fp_oh_enc_gbdt = \"gbdt/oh_enc_gbdt\"\n",
    "\n",
    "## 预训练模型的存储\n",
    "\n",
    "fp_gbdt_model = \"gbdt/gbdt_model.pkl\"\n",
    "\n",
    "## 提交的数据\n",
    "fp_sub_gbdt = \"gbdt/GBDT_submission.csv\"\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-12T05:12:39.662628Z",
     "start_time": "2019-03-12T05:12:39.640690Z"
    }
   },
   "outputs": [],
   "source": [
    "##==================== GBDT 模型 ====================##\n",
    "## feature names\n",
    "cols = ['C1',\n",
    "        'banner_pos', \n",
    "        'site_domain', \n",
    "        'site_id',\n",
    "        'site_category',\n",
    "        'app_id',\n",
    "        'app_category', \n",
    "        'device_type', \n",
    "        'device_conn_type',\n",
    "        'C14', \n",
    "        #'C15',\n",
    "        #'C16',\n",
    "        'date',\n",
    "        'time_period',\n",
    "        'weekday',\n",
    "        'C15_C16'  ]\n",
    "\n",
    "cols_train = ['id', 'click']\n",
    "cols_test  = ['id']\n",
    "cols_train.extend(cols)\n",
    "cols_test.extend(cols)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-12T05:13:23.000956Z",
     "start_time": "2019-03-12T05:12:49.275255Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "25"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#----- data for GBDT (label encoding) -----#\n",
    "df_train = pd.read_csv(fp_train_f,dtype={'id':str})  # data load\n",
    "\n",
    "\n",
    "## label 编码的转换\n",
    "label_enc = pickle.load(open(fp_lb_enc, 'rb'))\n",
    "for col in cols:\n",
    "    df_train[col] = label_enc[col].fit_transform(df_train[col].values)\n",
    "\n",
    "## 为GBDT 和LR 模型训练分别分割数据\n",
    "## 这为了防止过拟合\n",
    "X_train_org = df_train[cols].get_values()\n",
    "y_train_org = df_train['click'].get_values()\n",
    "\n",
    "# 30% 做验证集，70%做训练集\n",
    "X_train_gbdt, X_valid, y_train_gbdt, y_valid = train_test_split(X_train_org, y_train_org, test_size = 0.3, random_state = 0)\n",
    "\n",
    "\n",
    "del df_train\n",
    "\n",
    "gc.collect()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-12T05:13:37.959415Z",
     "start_time": "2019-03-12T05:13:37.934482Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "GradientBoostingClassifier(criterion='friedman_mse', init=None,\n",
       "                           learning_rate=0.15, loss='deviance', max_depth=7,\n",
       "                           max_features=None, max_leaf_nodes=None,\n",
       "                           min_impurity_decrease=0.0, min_impurity_split=None,\n",
       "                           min_samples_leaf=22, min_samples_split=85,\n",
       "                           min_weight_fraction_leaf=0.0, n_estimators=48,\n",
       "                           n_iter_no_change=None, presort='auto',\n",
       "                           random_state=1, subsample=0.01, tol=0.0001,\n",
       "                           validation_fraction=0.1, verbose=0,\n",
       "                           warm_start=False)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#----- GBDT 模型训练-----#\n",
    "#----- 使用调完参以后的参数-----#\n",
    "\n",
    "params = {  # init the hyperparams of GBDT\n",
    "    'learning_rate': 0.15,\n",
    "    'n_estimators': 48,  # number of trees here\n",
    "    'max_depth': 7,  # set max_depth of a tree\n",
    "    'min_samples_split': 85, \n",
    "    'min_samples_leaf': 22,\n",
    "    'subsample': 0.01, \n",
    "    'max_leaf_nodes': None,  # set max leaf nodes of a tree\n",
    "    'random_state': 1,\n",
    "    'verbose': 0\n",
    "    }\n",
    "\n",
    "gbdt_model = GradientBoostingClassifier()\n",
    "gbdt_model.set_params(**params)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## fitting\n",
    "gbdt_model.fit(X_train_gbdt, y_train_gbdt)\n",
    "gc.collect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "log loss of GBDT on train set: 0.41253\n",
      "log loss of GBDT on valid set: 0.41271\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## log-loss of training\n",
    "y_pred_gbdt = gbdt_model.predict_proba(X_train_gbdt)[:, 1]\n",
    "log_loss_gbdt = log_loss(y_train_gbdt, y_pred_gbdt)\n",
    "print('log loss of GBDT on train set: %.5f' % log_loss_gbdt)\n",
    "\n",
    "y_pred_gbdt = gbdt_model.predict_proba(X_valid)[:, 1]\n",
    "log_loss_gbdt = log_loss(y_valid, y_pred_gbdt)\n",
    "print('log loss of GBDT on valid set: %.5f' % log_loss_gbdt)\n",
    "\n",
    "gc.collect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## store the pre-trained gbdt_model\n",
    "pickle.dump(gbdt_model, open(fp_gbdt_model, 'wb'))\n",
    "\n",
    "del X_train_gbdt\n",
    "del y_train_gbdt\n",
    "gc.collect()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "##==================== 预测 ====================##\n",
    "df_test_f = pd.read_csv(fp_test_f, \n",
    "                        index_col=None,  dtype={'id':str}, \n",
    "                        chunksize=10000, iterator=True)        \n",
    "\n",
    "hd = True\n",
    "for chunk in df_test_f:\n",
    "    ## label transform for training set\n",
    "    for col in cols:\n",
    "        chunk[col] = label_enc[col].fit_transform(chunk[col].values)       \n",
    "    X_test = chunk[cols].get_values()\n",
    "    \n",
    "    #----- GBDT-LR -----#\n",
    "    y_pred_gbdt = gbdt_model.predict_proba(X_test)[:, 1]\n",
    "   \n",
    "    \n",
    "    #----- 生成submission -----#\n",
    "   \n",
    "    chunk['click'] = y_pred_gbdt\n",
    "    with open(fp_sub_gbdt, 'a') as f: \n",
    "        result_df = pd.DataFrame({'id':chunk['id'],'click':chunk['click']})\n",
    "        result_df.to_csv(f, columns=['id', 'click'], header=hd, index=False)\n",
    "    \n",
    "    hd = False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1.0,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
